<template>
  <div class="p-4">
    <div class="add_project">
      <a-button type="primary" @click="addOrEditAnnouncementsFn('add')" v-if="haveAdd"
        >添加资料</a-button
      >
    </div>
    <div class="ant_table">
      <Table
        style="height: 100%"
        :dataSource="dataSource"
        :columns="columns"
        :pagination="pagination"
        @change="tableChangeFn"
      >
        <!-- <template #contract="{ record }">
          <div class="file_download" @click="fileDownloadFn(record)">附件下载</div>
        </template> -->
        <template #action="{ record }">
          <div class="action">
            <div @click="addOrEditAnnouncementsFn('edit', record)" v-if="haveAdd">修改</div>

            <Popconfirm
              :title="`您确定要删除${record.name}吗？`"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirmDeletion(record)"
            >
              <div v-if="haveAdd">删除</div>
            </Popconfirm>
          </div>
        </template>
        <template #designResponseUrl="{ record }">
          <div v-if="record?.urls" class="file_download" @click="fileDownloadFn(record)"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>
      </Table>
    </div>
    <!-- 新增/编辑公告弹窗 -->
    <AddOrEdit ref="addOrEditRef" @reload="getTableData"></AddOrEdit>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { Form, FormItem, DatePicker, Upload, InputNumber, notification } from 'ant-design-vue';
  import { Table, message, Popconfirm } from 'ant-design-vue';
  import { getdataCenter, removeDataCenter } from '/@/api/announcements';
  import { fileDownloadApi, getMyCompanyInfoApi } from '/@/api/projectManagement';
  import AddOrEdit from './components/addOrEdit.vue';
  import axios from 'axios';
  const columns = ref([
    {
      title: '名称',
      dataIndex: 'name',
      width: 330,
      align: 'left',
      // ellipsis: true,
    },
    {
      title: '附件',
      dataIndex: 'urls',
      slots: { customRender: 'designResponseUrl' },
      align: 'left',
      width: 100,
    },
    {
      title: '备注',
      dataIndex: 'comment',
      // width: 300,
      align: 'left',
      // ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'left',
      // ellipsis: true,
      width: 200,
    },
    {
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      width: 100,
      align: 'left',
      // ellipsis: true,
    },
  ]);
  const dataSource = ref([]);
  const haveAdd = ref(false);
  onMounted(() => {
    getTableData();
    getMyCompanyInfoApi().then((res) => {
      if (res?.id == 10000000) {
        haveAdd.value = true;
      } else {
        haveAdd.value = false;
      }
    });
  });
  const getTableData = () => {
    getdataCenter({
      page: pagination.value.current,
      limit: pagination.value.pageSize,
    }).then((res) => {
      pagination.value.total = res.total;
      dataSource.value = res.items;
    });
  };
  const fileDownloadFn = (record) => {
    notification.open({
      message: '提示',
      description: '文件下载中...',
      duration: 0,
    });
    for (let i in record.urls) {
      // fileDownloadApi(`${record.urls[i]}`).then((res) => {
      //   download(res, `${record.name}${Number(i) + 1}.${record.urls[i].split('.')[1]}`);
      // });
      axios
        .get(`https://admin-api.gongcheng1949.com/v1/file/download?url=${record.urls[i]}`, {
          responseType: 'blob',
        })
        .then((res) => {
          if (res.status == 200) {
            download(res.data, `${record.name}${Number(i) + 1}.${record.urls[i].split('.')[1]}`);
          } else {
            notification.destroy();
            message.error('下载失败');
          }
        })
        .catch((error) => {
          notification.destroy();
          message.error('下载失败');
        });
    }
  };
  // blob下载
  const download = (blob, name) => {
    const link = document.createElement('a'); //创建一个a标签
    const url = window.URL.createObjectURL(blob); //将blob文件对象通过URL.createObjectURL()方法转为为url
    link.href = url; //为a标签设置href属性，并赋值为url
    link.download = name; //定义下载的文件名，文件名要包含后缀哟！如'导出EXCEL.xlsx'
    document.body.appendChild(link); //把a标签放在body上
    link.click(); //出发a标签点击下载
    document.body.removeChild(link); //在body中移除这个a标签
    URL.revokeObjectURL(url); //释放blob对象
    notification.destroy();
  };

  // table变化时出发  筛选/跳转
  const tableChangeFn = (e) => {
    pagination.value.current = String(e.current);
    pagination.value.pageSize = String(e.pageSize);
    console.log(e, 'e');
    getTableData();
  };

  //分页器对象
  const pagination = ref({
    current: '1',
    pageSize: '10',
    pageSizeOptions: ['10', '20', '50', '100'],
    total: 0,
    showTotal: (totals) => `总${totals}条数据`,
    showSizeChanger: true,
  });

  // 打开 新增编辑弹窗
  const addOrEditRef = ref();
  const addOrEditAnnouncementsFn = (action, record?) => {
    let data;
    if (action == 'add') {
      data = {};
    } else {
      data = {
        id: record.id,
        name: record.name,
        urlArr: record.urls,
        comment: record.comment,
      };
    }
    addOrEditRef.value.init(data);
  };

  // 删除
  const confirmDeletion = (record) => {
    removeDataCenter({
      id: record.id,
    }).then((res) => {
      if (res != false) {
        message.success('删除成功');
        getTableData();
      }
    });
  };
</script>

<style lang="less" scoped>
  .add_project {
    margin-bottom: 10px;
  }
  .action {
    > div {
      text-align: left;
      color: #1990ff;
      cursor: pointer;
      margin: 5px 0;
    }
  }
  .file_download {
    cursor: pointer;
    color: rgba(0, 175, 233);
  }
</style>
